<template>
  <div ref="container"></div>
</template>

<script>
import { ref, onMounted } from "vue";
import {
  PivotSheet,
  S2Event,
  DataCell,
  RowCell,
  ColCell,
  CustomText,
  renderText,
  getEmptyPlaceholder,
} from "@antv/s2";

export default {
  setup() {
    const container = ref(null);
    let s2;

    onMounted(() => {
      class CustomColCell extends ColCell {
        drawTextShape() {
          const { x, y, width, height, value } = this.getMeta();
          const text = String(value || ""); // 获取单元格文本内容

          const textStyle = {
            fontSize: 18,
            fill: "#000",
            textAlign: "left",
            textBaseline: "middle", // 垂直基线
          };

          const lineHeight = 1 * textStyle.fontSize; // 行高
          const padding = 6; // 内边距

          const availableWidth = width - 2 * padding; // 可用绘制宽度

          // 文本分行逻辑
          const lines = [];
          let currentLine = "";
          [...text].forEach((char) => {
            const tempLine = currentLine + char;
            const tempLineWidth = tempLine.length * textStyle.fontSize; // 简单估算文本宽度
            if (tempLineWidth > availableWidth) {
              lines.push(currentLine); // 当前行完成
              currentLine = char; // 开始新行
            } else {
              currentLine = tempLine; // 当前行继续添加
            }
          });
          if (currentLine) {
            lines.push(currentLine); // 添加最后一行
          }

          // 计算文本总高度并居中
          const totalTextHeight = lines.length * lineHeight;
          console.log(y, height, totalTextHeight, lines.length, lines);
          const startY = y + (height - totalTextHeight) / 2; // 起始 Y 坐标

          // 绘制每行文本
          lines.forEach((line, lineIndex) => {
            let lineY = 0;
            if (lineIndex == 0) {
              lineY = startY + lineIndex * lineHeight; // 当前行的 Y 坐标
            } else {
              lineY = startY + lineIndex * lineHeight + padding; // 当前行的 Y 坐标
            }
            const totalChars = line.length; // 当前行字符数

            // 计算字符间距（分散对齐）
            const spaceBetween =
              totalChars > 1
                ? (availableWidth - textStyle.fontSize * totalChars) /
                  (totalChars - 1)
                : 0;

            // 起始 X 坐标
            let startX = x + padding;

            // 绘制每个字符
            [...line].forEach((char, charIndex) => {
              const charX =
                startX + charIndex * (textStyle.fontSize + spaceBetween); // 当前字符 X 坐标
              const textShape = renderText({
                group: this,
                textShape: [this.textShape],
                style: {
                  ...textStyle,
                  x: charX,
                  y: lineY,
                  text: char,
                },
              });
              this.addTextShape(textShape);
            });
          });

          console.log(this.textShapes); // 打印绘制的文本形状调试
        }
        // drawTextShape() {
        //   const { x, y, width, height, value } = this.getMeta();
        //   const text = String(value || ''); // 单元格文本内容
        //   const textStyle = {
        //     fontSize: 12,
        //     fill: '#000',
        //     textAlign: 'center',
        //     textBaseline: 'middle',
        //   };
        //
        //   // 计算文本绘制的中心位置
        //   var centerX = x + width / 2;
        //   const centerY = y + height / 2;
        //   console.log(text);
        //   [...text].forEach((char, index) => {
        //     this.textShape = renderText({
        //       group: this,
        //       textShape: [this.textShape],
        //       style: {
        //         ...textStyle,
        //         x: x + 20*index, // 水平居中
        //         y: y + height / 2, // 垂直排列
        //         wordWrap: true,
        //         // 文本必须为字符串
        //         text: `${char}`,
        //       },
        //     });
        //
        //     this.addTextShape(this.textShape);
        //   });
        //   console.log(this.textShapes)
        // }
      }

      class CustomRowCell extends RowCell {
        initCell() {
          // 获取单元格的元数据
          const { x, y, width, height, value } = this.meta;
          // this.meta.height = 200; // 动态调整单元格高度
          // 调用父类的初始化方法
          super.initCell();
          // 清除默认的文本
          this.clearTextShapes();
          // 获取单元格文本，并将其拆分为单个字符
          const characters = value.split("").join("\n"); // 使用 getFieldValue 方法

          const shape = this.renderTextShape({
            text: characters,
            x: x + width / 2, // 水平居中
            y: y + height / 2, // 垂直排列
            textAlign: "center", // 水平对齐方式
            textBaseline: "center", // 垂直基线
            fontSize: 12, // 字体大小
            fill: "#000", // 文字颜色
          });

          this.textShapes.push(shape);
        }

        // 清除文本形状
        clearTextShapes() {
          if (this.textShapes) {
            this.textShapes.forEach((shape) => shape.remove());
            this.textShapes = [];
          }
        }

        // drawTextShape() {
        //   // super.initCell();
        //
        //   // 获取单元格的元数据信息
        //   const { x, y, width, height, value } = this.meta;
        //   // 拆分文本值为单个字符
        //   const { formattedValue } = this.getFormattedFieldValue();
        //   const maxTextWidth = this.getMaxTextWidth();
        //   const textStyle = this.getTextStyle();
        //   const {
        //     options: { placeholder },
        //     measureTextWidth,
        //   } = this.spreadsheet;
        //   const emptyPlaceholder = getEmptyPlaceholder(this, placeholder);
        //   const ellipsisText = "12124123213";
        //
        //   this.actualText = ellipsisText;
        //   this.actualTextWidth = measureTextWidth(ellipsisText, textStyle);
        //   const position = this.getTextPosition();
        //   // 右下角绘制
        //   this.textShape = renderText(
        //       this,
        //       [this.textShape],
        //       position.x,
        //       position.y,
        //       ellipsisText,
        //       textStyle
        //   );
        //
        //   this.textShapes.push(this.textShape);
        // }
      }

      class CustomDataCell extends DataCell {
        getFieldValue() {
          // 获取行 ID 和列 ID
          const { x, y, rowId, colId } = this.getMeta();
          // 分割 `rowId` 和 `colId` 获取具体字段
          const rowFields = rowId.split("[&]").slice(1); // 跳过 'root'
          const colFields = colId.split("[&]").slice(1); // 跳过 'root'

          // 遍历 `displayData` 查找匹配的记录
          const data = this.spreadsheet.dataSet.displayData;
          const valuesField = this.spreadsheet.dataSet.fields.values[0]; // 获取 'value' 字段

          let value = null;
          for (const item of data) {
            // 判断 `rowFields` 和 `colFields` 是否都匹配
            const isRowMatch = rowFields.every(
              (field) => item[field] !== undefined
            );
            const isColMatch = colFields.every(
              (field) => item[field] !== undefined
            );

            if (isRowMatch && isColMatch) {
              value = item[valuesField]; // 获取数据值
              break;
            }
          }

          return value;
        }
      }

      const customTree = [
        {
          field: "a-1",
          title:
            "财政教育经费投入收到捡垃圾几点几分解决法鸡打两局基督教啊了解倒垃圾的",
          wordTR: "vl",
          children: [
            {
              field: "a-1-1",
              title: "项目经费",
              children: [
                {
                  field: "bzhjs",
                  title: "标准化建设",
                  children: [],
                },
                {
                  field: "xxhjs",
                  title: "信息化建设",
                  children: [],
                },
              ],
            },
            {
              field: "a-1-2",
              title: "基础拨款",
              children: [],
            },
          ],
        },
        {
          field: "a-2",
          title: "其他投入",
          children: [],
        },
      ];

      // 定义省市县的自定义树形结构
      const rowsTreeHierarchy = [
        {
          field: "beijing",
          title: "北京市",
          wordTR: "vl",
          description: "北京省描述",
          children: [
            {
              field: "haidian",
              title: "海淀区",
              wordTR: "vl",
              description: "海淀区描述",
              children: [
                {
                  field: "zizhuyuan",
                  title: "紫竹院",
                  description: "紫竹院描述",
                  children: [],
                },
                {
                  field: "zhongguancun",
                  title: "中关村",
                  description: "中关村描述",
                  children: [],
                },
              ],
            },
          ],
        },
        {
          field: "shanghai",
          title: "上海市",
          description: "上海省描述",
          children: [
            {
              field: "huangpu",
              title: "黄浦区",
              description: "黄浦区描述",
              children: [],
            },
          ],
        },
      ];

      const data = [
        {
          beijing: "北京市",
          haidian: "海淀区",
          zizhuyuan: "紫竹院",
          "a-1": "财政教育经费投入",
          "a-1-1": "项目经费",
          bzhjs: "标准化建设",
          value: 12121,
        },
        {
          beijing: "北京市",
          haidian: "海淀区",
          zizhuyuan: "紫竹院",
          "a-1": "财政教育经费投入",
          "a-1-1": "项目经费",
          xxhjs: "信息化建设",
          value: 322,
        },
        {
          beijing: "北京市",
          haidian: "海淀区",
          zizhuyuan: "紫竹院",
          "a-1": "财政教育经费投入",
          "a-1-2": "基础拨款",
          value: 555,
        },
        {
          shanghai: "上海市",
          huangpu: "黄浦区",
          "a-1": "财政教育经费投入",
          "a-1-2": "基础拨款",
          value: 2127,
        },
      ];

      const s2DataConfig = {
        fields: {
          rows: rowsTreeHierarchy,
          columns: customTree,
          values: ["value"],
        },
        data,
      };

      const s2Options = {
        width: 800,
        height: 1200,
        colCell: (node, spreadsheet, headerConfig) => {
          return new CustomColCell(node, spreadsheet, headerConfig);
        },
        dataCell: (viewMeta, spreadsheet) => {
          return new CustomDataCell(viewMeta, spreadsheet);
        },
        rowCell: (node, spreadsheet, headerConfig) => {
          return new CustomRowCell(node, spreadsheet, headerConfig);
        },
        hierarchyType: "grid",
        style: {
          rowCell: {
            // 固定配置: 行头单元格 100px
            // width: 100,
            // 动态配置: 叶子节点 300px, 非叶子节点 200px
            height: (node) => {
              const text = node.value;
              const words = text.split("");

              return words.length * 35;
            },
          },
          colCell: {
            height: 50,
          },
          colCfg: {
            width: 100,
          },
        },
      };

      // 初始化 S2 实例
      s2 = new PivotSheet(container.value, s2DataConfig, s2Options);
      s2.render();
    });

    return {
      container,
    };
  },
};
</script>

<style scoped>
.container {
  margin: 20px;
}
</style>
